'use strict';

const Koa = require('koa');
const body = require('koa-body');
const staticFile = require('koa-static');
const path = require('path');
const temp = require('./templating')
const cons = require('./controller');
const { sequelize, objMod } = require('./models');
const session = require('koa-session');


//判断是否连接成功
(async () => {
    try {
        sequelize.authenticate();
        console.log('连接成功');
    } catch (error) {
        console.log('连接失败');
    }
})();

let app = new Koa();
let port = 3000;

app.use(body());

//模板渲染中间件
app.use(temp)

//配置session
app.keys = ['some secret hurr'];

const CONFIG = {
    key: 'koa.sess', /** 默认值 */
    maxAge: 60 * 1000 * 10, //10 分钟  /*用户过期时间（以毫秒为单位）*/ 
    autoCommit: true, /** 是否自动提交到响应头 */
    overwrite: true, /** (boolean) can overwrite or not (default true) 没有效果，默认*/
    httpOnly: true, /** 表示只有服务器端可以获取cookie的值（true） */
    signed: true, /** 默认，签名 */
    rolling: false, /** 重置coolie的过期时间*/
    renew: true, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
    // secure: true, /** (boolean) secure cookie*/
    // sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};

app.use(session(CONFIG, app));

//路由中间件
app.use(cons());

//配置静态路由
app.use(staticFile(path.join(__dirname, 'static')));

app.use(async (ctx, next) => {
    console.log("当前时间：" + new Date());

    if (ctx.status == 404) {
        ctx.render('404.html', {});
    }
    await next();
});

// (async()=>{
//     await objMod.Comment.sync({force: true});
//     await objMod.Message.sync({ force: true })
//     await objMod.Like.sync({ force: true })
//     console.log("建表成功");
// })();

app.listen(port, () => {
    console.log(`http://127.0.0.1:${port}`);
})